﻿using ERPWinFormWork.Test.Test.Dtos;
using ERPWinFormWork.Test.TestCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Test
{
    public partial class GetInspection : Form
    {
        private ApiClient _apiClient;
        private readonly Action<List<Testing_ItemsDtos>> _onSelected;

        public GetInspection(Action<List<Testing_ItemsDtos>> onSelected = null)
        {
            _apiClient = new ApiClient(TestAPI.TestApiBaseUrl);
            InitializeComponent();
            _onSelected = onSelected;

            // 事件绑定
            this.btnChange.Click += btnChange_Click;
            this.dgvInspectionView.CurrentCellDirtyStateChanged += dgvInspectionView_CurrentCellDirtyStateChanged;

            // 首次加载
            GetData();
        }


        private async void GetData(Dictionary<string, string> customParams = null)
        {
            var response = await _apiClient.GetAsync<TestApiResult<List<Testing_ItemsDtos>>>(
                        endpoint: "api/Read/GetTesting_Items"
                    );

            // 处理响应结果
            if (response != null && response.code == 200)
            {
                // 配置列并绑定数据
                EnsureCheckBoxColumn();
                dgvInspectionView.AutoGenerateColumns = true;
                dgvInspectionView.DataSource = response.data;

                // 中文列头
                if (dgvInspectionView.Columns.Contains("Items_Name")) dgvInspectionView.Columns["Items_Name"].HeaderText = "检测项目";
                if (dgvInspectionView.Columns.Contains("DetectionType_Name")) dgvInspectionView.Columns["DetectionType_Name"].HeaderText = "检验类型";
                if (dgvInspectionView.Columns.Contains("Tools_Name")) dgvInspectionView.Columns["Tools_Name"].HeaderText = "检验工具";
            }
        }

        // 确保存在复选框列
        private void EnsureCheckBoxColumn()
        {
            const string checkColumnName = "colCheck";
            if (!dgvInspectionView.Columns.Contains(checkColumnName))
            {
                var col = new DataGridViewCheckBoxColumn
                {
                    Name = checkColumnName,
                    HeaderText = "选择",
                    Width = 60
                };
                dgvInspectionView.Columns.Insert(0, col);
            }
        }

        // 提交单元格编辑（确保勾选即时生效）
        private void dgvInspectionView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dgvInspectionView.IsCurrentCellDirty)
            {
                dgvInspectionView.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        // 选择按钮：回传勾选项
        private void btnChange_Click(object sender, EventArgs e)
        {
            if (_onSelected == null)
            {
                this.Close();
                return;
            }

            var selected = new List<Testing_ItemsDtos>();
            foreach (DataGridViewRow row in dgvInspectionView.Rows)
            {
                var cell = row.Cells["colCheck"] as DataGridViewCheckBoxCell;
                var isChecked = cell != null && cell.Value != null && Convert.ToBoolean(cell.Value);
                if (isChecked && row.DataBoundItem is Testing_ItemsDtos item)
                {
                    selected.Add(item);
                }
            }

            _onSelected(selected);
            this.Close();
        }
    }
}
